#' Find Index of Time Point Closest to Target
#'
#' This function takes a vector of time values and finds the index of the element
#' that is closest to a specified target time.
#'
#' @param time_vector A numeric vector of time values.
#' @param target_time A numeric scalar representing the target time to find.
#' @param time_unit A character string specifying the unit of `time_vector`.
#'   Possible values are "s" (seconds, default), "ms" (milliseconds), or "us"
#'   (microseconds). This determines the conversion factor applied to
#'   `time_vector` before comparing to `target_time`.
#'
#' @return An integer scalar representing the index of the closest time point in
#'   `time_vector`. If `time_vector` is empty, returns `NA_integer_`.
#'
#' @export
#'
#' @examples
#' # Time vector in seconds
#' times_sec = c(0.001, 0.002, 0.003, 0.004)
#' find_time_index(times_sec, target_time = 2.5, time_unit = "ms") # Should return 3
#'
#' # Time vector in milliseconds
#' times_ms = c(1, 2, 3, 4)
#' find_time_index(times_ms, target_time = 0.0025, time_unit = "s") # Should return 3
find_time_index = function(time_vector, target_time, time_unit = "s") {
  # Input validation
  if (!is.numeric(time_vector)) {
    stop("`time_vector` must be a numeric vector.")
  }
  if (!is.numeric(target_time) || length(target_time) != 1) {
    stop("`target_time` must be a single numeric value.")
  }
  if (length(time_vector) == 0) {
    warning("`time_vector` is empty. Returning NA.")
    return(NA_integer_)
  }
  
  # Define conversion factor from time_vector's unit to target_time's unit
  conversion_factor = switch(time_unit,
                              "s" = 1,
                              "ms" = 1e-3,
                              "us" = 1e-6,
                              stop("Unsupported `time_unit`. Use 's', 'ms', or 'us'."))
  
  # Convert time_vector to the same unit as target_time and find the closest index
  converted_time = time_vector * conversion_factor
  closest_index = which.min(abs(converted_time - target_time))
  
  return(closest_index)
}

